import config from './config.js';

// 请求拦截器
const requestInterceptor = (options) => {
    // 统一添加access_token
    const access_token = uni.getStorageSync('access_token');
    if (access_token) {
        options.header = {
            ...options.header,
            'Authorization': `Bearer ${access_token}`
        };
    }
    
    // 处理请求URL
    if (!options.url.startsWith('http')) {
        // 确保 baseUrl 不以斜杠结尾，options.url 不以斜杠开头
        const baseUrl = config.baseUrl.endsWith('/') ? config.baseUrl.slice(0, -1) : config.baseUrl;
        const url = options.url.startsWith('/') ? options.url : '/' + options.url;
        options.url = baseUrl + url;
    }
    
    return options;
};

// 响应拦截器
const responseInterceptor = (response) => {
    const { statusCode, data } = response;
    
    // 请求成功
    if (statusCode >= 200 && statusCode < 300) {
        return data;
    }
    
    // 401: 未登录或access_token过期
    if (statusCode === 401) {
        uni.showToast({
            title: '请先登录',
            icon: 'none'
        });
        
        // 清除access_token并跳转到登录页
        uni.removeStorageSync('access_token');
        
        // 获取当前页面路径用于登录后跳回
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        const url = `/${currentPage.route}`;
        const redirect = encodeURIComponent(url);
        
        // 跳转到登录页
        uni.navigateTo({
            url: `/pages/user/login?redirect=${redirect}`
        });
        
        return Promise.reject(new Error('未登录或登录已过期'));
    }
    
    // 其他错误
    uni.showToast({
        title: data.message || '请求失败',
        icon: 'none'
    });
    
    return Promise.reject(data);
};

// 封装请求方法
const request = (options) => {
    // 应用请求拦截器
    options = requestInterceptor(options);
    
    return new Promise((resolve, reject) => {
        uni.request({
            ...options,
            success: (res) => {
                try {
                    // 应用响应拦截器
                    const result = responseInterceptor(res);
                    resolve(result);
                } catch (error) {
                    reject(error);
                }
            },
            fail: (err) => {
                uni.showToast({
                    title: '网络异常，请稍后重试',
                    icon: 'none'
                });
                reject(err);
            }
        });
    });
};

// 封装常用请求方法
const http = {
    
    get(url, data = {}, options = {}) {
        return request({
            url,
            data,
            method: 'GET',
            ...options
        });
    },
    
    post(url, data = {}, options = {}) {
        return request({
            url,
            data,
            method: 'POST',
            ...options
        });
    },
    
    put(url, data = {}, options = {}) {
        return request({
            url,
            data,
            method: 'PUT',
            ...options
        });
    },
    
    delete(url, data = {}, options = {}) {
        return request({
            url,
            data,
            method: 'DELETE',
            ...options
        });
    },
    
    // 上传文件
    upload(url, filePath, formData = {}, options = {}) {
        // 应用请求拦截器
        const interceptedOptions = requestInterceptor({
            url,
            header: options.header || {}
        });
        
        return new Promise((resolve, reject) => {
            uni.uploadFile({
                url: interceptedOptions.url,
                filePath,
                name: options.name || 'file',
                formData,
                header: interceptedOptions.header,
                success: (res) => {
                    try {
                        // 上传接口返回的是字符串，需要转换为对象
                        if (typeof res.data === 'string') {
                            res.data = JSON.parse(res.data);
                        }
                        
                        // 应用响应拦截器
                        const result = responseInterceptor(res);
                        resolve(result);
                    } catch (error) {
                        reject(error);
                    }
                },
                fail: (err) => {
                    uni.showToast({
                        title: '上传失败，请稍后重试',
                        icon: 'none'
                    });
                    reject(err);
                }
            });
        });
    }
};

export default http; 